package cn.edu.mju.dal.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.mju.dal.ITeacherDAO;
import cn.edu.mju.db.DbHelper;
import cn.edu.mju.model.Teacher;
import cn.edu.mju.utils.Pager;

public class TeacherDAO implements ITeacherDAO {

	@Override
	public void save(Teacher t) {
		Session session = DbHelper.getSession();
		Transaction ts = session.beginTransaction();
		if(t.gettId() != null && t.gettId() > 0)
		{
			session.update(t);
		}
		else
		{
			session.save(t);
		}
		ts.commit();
		session.close();
		
	}

	@Override
	public void delete(Integer tId) {
		Session session = DbHelper.getSession();
		Transaction ts = session.beginTransaction();
		Teacher teacher = session.get(Teacher.class, tId);
		session.delete(teacher);
		ts.commit();
		session.close();
		
	}

	@Override
	public Pager findPager(Integer page, Teacher t) {
		Session session = DbHelper.getSession();		
		String hqlTotal = "select count(*) from Teacher where 1=1";
		String hqlSelect = "from Teacher order by id desc";
				
		StringBuffer hqlWhere = new StringBuffer("");    //UserGroup类名
		if(t.gettName() != null && !"".equals(t.gettName()))
		{
			hqlWhere.append("and tName like :tName ");
		}		
		Query query = session.createQuery(hqlTotal + hqlWhere.toString());
		
		if(t != null && t.gettName() != null && !"".equals(t.gettName()))
		{
			query.setString("tName","%" + t.gettName() + "%");
		}
		
		int rows = ((Long) query.getSingleResult()).intValue();		//条数
		Pager pager = new Pager();			//实例化翻页的方法 （调用Pager方法）
		pager.setRows(rows);
		pager.setPage(page);
		
		query = session.createQuery(hqlSelect + hqlWhere.toString());	//查询UserGroup数据,显示在列表
		if(t.gettName() != null && !"".equals(t.gettName()))
		{
			query.setString("tName","%" + t.gettName() + "%");
		}
		query.setFirstResult((pager.getPage()-1)* pager.getPageSize());
		query.setMaxResults(pager.getPageSize());
		pager.setData(query.list());
		//pager.getPages();
		session.close();
		return pager;
	}

	@Override
	public Teacher findById(Integer tId) {
		Session session = DbHelper.getSession();
		String hql = "from Teacher where tId=:tId";
		Query query = session.createQuery(hql);
		query.setInteger("tId", tId);
		Teacher teacher = (Teacher) query.getSingleResult();
		session.close();
		return teacher;
	}

	@Override
	public List<Teacher> findAll(Teacher t) {
		Session session = DbHelper.getSession();
		String hql = new String("from Teacher where 1=1");
		Query query = session.createQuery(hql);
		List<Teacher> list = query.list();
		return list;
	}

}
